//app.js
// lingyoupin-2
// var aldstat = require("./utils/ald-stat.js");
// http://test2.xingliaoapp.com
// https://lingyoupin.xingliaoapp.com
const appid_from = 2;
var loginInfo = {};
App({
  setConfig: {
    url: 'https://lingyoupin.xingliaoapp.com/api/v2', type: 'site_config', version: '64'
  },
  onLaunch: function (options) {
    var _this = this;
    // console.log("app lanuch运行");
    // console.log(options);
    var uid;
    var scene = decodeURIComponent(options.query.scene);
    if (scene && scene !== 'undefined') {
      //扫码进入注册
      var sceneParams = new Array();
      sceneParams = scene.split('#');
      var theUserShareId = sceneParams[1];//用户ID
      console.log("lanunch 运行uid");
      console.log(theUserShareId);
      uid = theUserShareId;
    } else {
      var theUserShareId = options.query.uid;
      if (theUserShareId && theUserShareId !== 'undefined') {
        console.log('lanunch 分享图片进入');
        uid = theUserShareId;
      }
    }
    _this.userLogin(uid);
    _this.checkAuthioze(success => {
      
    }, fail => {
      //未授权提示用户授权
    //  wx.navigateTo({
    //    url: '/pages/home/home?is_authorization=1',
    //  })
    });
  },
  data: {
    extra: null,
  },
  onShow: function (e) {
    this.data.extra = e;
  },
  globalData: {
    // longitude: null,
    // latitude: null,
    userInfo: null,
    token: '',
    timer: null,
    hotTitle: '',
    randCode: [

    ],
    code: null,
    defaultConfigs: null
  },
  //登录
  userLogin: function (uid = 0) {
    var that = this;
    var codes;
    wx.setStorageSync('token', null);
    wx.setStorageSync('cash', null);
    //获取登录code
    wx.login({
      success: function (res) {
        if (res.code) {
          loginInfo.code = res.code;
          that.globalData.code = res.code
          codes = res.code;
          //获取用户信息
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                //  已经授权，可以直接调用  getUserInfo  获取头像昵称，不会弹框
                wx.getUserInfo({
                  success: res => {
                    //  可以将  res  发送给后台解码出  unionId
                    var infoUser = '';
                    that.globalData.userInfo = infoUser = res.userInfo;
                    //  所以此处加入  callback  以防止这种情况
                    if (that.userInfoReadyCallback) {
                      that.userInfoReadyCallback(res)
                    }
                    //用户信息入库
                    var url = that.setConfig.url + '/Login/doLogin';
                    var data = {
                      // longitude: that.globalData.longitude,
                      // latitude: that.globalData.latitude,
                      user_name: infoUser.nickName,
                      nick_name: infoUser.nickName,
                      head_img: infoUser.avatarUrl,
                      sex: infoUser.gender,
                      coutry: infoUser.country,
                      city: infoUser.city,
                      province: infoUser.province,
                      code: codes,
                      encryptedData: res.encryptedData,
                      signature: res.signature,
                      ctype: that.setConfig.type,
                      version: that.setConfig.version,
                      iv: res.iv,
                      uid: uid
                    }
                    that.postLogin(url, data);
                  }
                })
              } else {
              }
            }
          });
        } else {
          that.userLogin(uid);
          return false;
        }
      }
    })
  },
  //提交
  postLogin: function (url, data, callback = function () { }) {
    var that = this;
    data.appid_from = appid_from;
    //发起网络请求
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        if (res.data.code != 2000) {
          if (res.data.code == 300001) {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false
            });
            callback(res);
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'loading',
              mask: true,
              duration: 1500
            });
          }

          return false;
        }
        if (res.data.token) {
          that.globalData.token = res.data.token;
          var stro_token = wx.getStorageSync('token');
          if (stro_token != res.data.token) {
            //重新处理token
            wx.setStorageSync('token', res.data.token);
            wx.setStorageSync('cash', res.data.data.cash);
          
            //加载全局配置选项
          }
            that.getInitConfig();
        } else {
          wx.showToast({
            title: '授权失败请重新进入',
            mask: true,
            duration: 1500
          });
        }
        callback(res);
      }
    })
  },
  onError: function (errMsg) {
    //Todo 程序出现问题（脚本发生错误，API调用失败保存错误信息）
  },
  wxPost: function (url, data, callback = function () { }) {
    var _this = this;
    data.appid_from = appid_from;
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        if (res.data.code != 2000) {
          wx.showToast({
            title: res.data.msg,
            icon: 'loading',
            mask: true,
            duration: 1500
          });
        }
        callback(res);
      }
    });
  },
  // post请求
  post: function (cmd, params, callback) {
    var _this = this;
    params.appid_from = appid_from;
    var token = _this.globalData.token;
    wx.request({
      url: _this.setConfig.url + cmd,
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: (res) => {
        wx.hideToast();
        if (typeof (callback) == 'function')
          callback(res.data);
      }
    })
  },
  // 获取公共配置文件
  getInitConfig: function () {
    var _this = this;
    var requestData = {
      token: _this.globalData.token,
      version: _this.setConfig.version,
      type: _this.setConfig.type
    }
    _this.post('/GlobalConfig/getInitConfig', requestData, function (res) {
      if (res.code == 2000) {
        wx.setStorageSync('configs',"");
        wx.setStorageSync('initConfig',"");
        wx.setStorageSync('configs', res.data.configs);
        wx.setStorageSync('initConfig', res.data);
      }
    });
  },
  // 收集用户的FormId
  postFormId: function (token, formid) {
    var that = this;
    var requestParams = {
      token: token,
      form_id: formid,
      version: that.setConfig.version,
      type: that.setConfig.type
    }
    that.post("/CollectEvent/FormId", requestParams, function (response) {
      console.log(response);
    });
  },
  /*检查权限控制*/
  checkAuthioze: function (success, fail) {
    wx.getSetting({
      success: (res) => {
        console.log(res);
        console.log(res.authSetting['scope.userInfo'])
        if (!res.authSetting['scope.userInfo']) {
          // console.log('执行了判断了吗');
            fail();
          // wx.authorize({
          //   scope: 'scope.userInfo',
          //   fail: error => {
          //     fail();
          //   },
          //   success: () => {
          //     success();
          //   }
          // });
        } else {
          success();
        }
      }
    });
  },
  // 获取用户的步数
  checkWeRunData: function (callback, failCallBack) {
    let that = this;
    wx.getSetting({
      success: (res) => {
        //检查用户是否已经授权过
        if (!res.authSetting['scope.werun']) {
          //未授权
          wx.getWeRunData({
            success(runres) {
              callback(runres);
              //  that.getStep(runres);
            },
            fail(err) {
              failCallBack(err);
            }
          });
        } else {
          //已授权
          wx.getWeRunData({
            success(runres) {
              callback(runres);
              // that.getStep(runres);
            },
            fail(err) {
              failCallBack(err);
            }
          });
        }
      }
    })
  },
  // 调用获取步数的接口
  getStep: function () {
    var that = this;
    that.checkWeRunData(
      (res) => {
        var requestData = {
          encryptedData: res.encryptedData,
          iv: res.iv,
          token: that.globalData.token,
          version: that.setConfig.version,
          type: that.setConfig.type
        }
        that.post('/User/updateWeRunData', requestData, function (res) { });
        // that.getGoodsList();
      },
      (err) => {
        //that.loadGoodsList();
        that.checkWeRunData(() => { }, () => { });
        console.log("调用失败");
      }
    );
  },
  /*文件上传*/
  uploadFile: function (data, callback = function () { }, fail = function () { }) {
    var that = this;
    var uploadResult = wx.uploadFile({
      url: that.setConfig.url + data.url,
      filePath: data.src,
      name: data.name,
      formData: {
        token: wx.getStorageSync('token')
      },
      success: (resp) => {
        callback(resp);
      },
      fail: (error) => {
        fail(error);
      }
    })
  },
  getCart: function (key = "") {
    var carts = wx.getStorageSync("goodsCookie");
    return carts;
  },
  getCookie: function (callback = function () { }) {
    wx.getStorage({
      key: 'goodsCookie',
      complete: function (res) {
        callback(res);
      }
    })
  },
  uploadCart: function (key, value, callback = function () { }) {
    var cookies = {
      "freight": "",
      "goods_id": "",
      "carousel_img": "",
      "detail_img": "",
      "name": "",
      "describe": "",
      "total_num": "",
      "gold_coin": 50,
      "is_new": "",
      "category_tag": "",
      "province_name": "",
      "city_name": "",
      "county_name": "",
      "detail_info": "",
      "tel_number": "",
      "express_name": "",
      "delay_id": "",
      "get_type": "",
      "help_num": "",
      "auction_id": "",
      "express_type": "",
      "audit_status": "",
      "audit_info": "",
      "buy_price": "",
      "original_price": ""
    }
    wx.getStorage({
      key: 'goodsCookie',
      complete: function (res) {
        if (res.data) {
          cookies = res.data;
        }
        cookies[key] = value;
        wx.setStorageSync("goodsCookie", cookies);
        callback();
      }
    })
  },
  uploadSync: function (key, value) {
    var cookies = {
      "freight": "",
      "goods_id": "",
      "carousel_img": "",
      "detail_img": "",
      "name": "",
      "describe": "",
      "total_num": "",
      "gold_coin": 50,
      "is_new": "",
      "category_tag": "",
      "province_name": "",
      "city_name": "",
      "county_name": "",
      "detail_info": "",
      "tel_number": "",
      "express_name": "",
      "delay_id": "",
      "get_type": "",
      "help_num": "",
      "auction_id": "",
      "express_type": "",
      "audit_status": "",
      "audit_info": "",
      "buy_price": "",
      "original_price": ""
    }
    var cookies = wx.getStorageSync("goodsCookie");
    if (cookies) {
      cookies[key] = value;
      wx.setStorageSync("goodsCookie", cookies);
    }
  },
  checkCart: function (callback = function () { }) {
    var cookies = wx.getStorageSync("goodsCookie");
    if (cookies.gold_coin <= 0 || cookies.gold_coin) {
      wx.showToast({
        title: '请填写商品金币数',
      })
      return false;
    }
    if (cookies.total_num <= 0 || cookies.total_num == "") {
      wx.showToast({
        title: '请填写商品数量',
      })
      return false;
    }
    if (cookies.buy_price <= 0 || cookies.buy_price == "") {
      wx.showToast({
        title: '请填写商品价格',
      })
      return false;
    }
    if (cookies.original_price <= 0 || cookies.original_price == "") {
      wx.showToast({
        title: '请填写商品原价',
      })
      return false;
    }
    callback();
  },
  //删除购物车
  removeCart: function () {
    wx.removeStorageSync("goodsCookie");
  },
  // 获取公共配置
  
})